package com.wang.diaryauth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.wang.diaryauth.enums.ResponseCodeEnum;
import com.wang.diaryauth.model.vo.verificationcode.SendVerificationCodeReqVO;
import com.wang.diaryauth.service.VerificationCodeService;
import com.wang.framework.common.constant.RedisKeyConstants;
import com.wang.framework.common.exception.BizException;
import com.wang.framework.common.response.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author : wangs
 * @date : 2024/10/31 0:00
 * @modyified By :
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        // 1、获取手机号
        String phone = sendVerificationCodeReqVO.getPhone();
        // 2、生成key
        String verificationCodeKey = RedisKeyConstants.buildVerificationCodeKey(phone);
        // 3、验证是否已生成验证码
        Boolean isKey = redisTemplate.hasKey(verificationCodeKey);

        if (isKey) {
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }
        // 4、生成验证码
        String ver_code = RandomUtil.randomNumbers(6);

        // todo 5、接入第三方短信发送验证码
        log.info("调用第三方发送验证码=》{}",ver_code);
        // 6、将发出的验证码存入redis
        redisTemplate.opsForValue().set(verificationCodeKey,ver_code,30, TimeUnit.MINUTES);

        return Response.success();
    }
}
